import axios from 'axios';
import type { AxiosRequestConfig, AxiosRequestHeaders } from 'axios';
import constants from '@/common/constants';
import { useUserInfo } from '@/stores/userInfo';

const instance = axios.create({
  // baseURL: constants.BASE_URL,
  timeout: 300000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
});
interface MyAxiosRequestConfig extends AxiosRequestConfig {
  api?: string;
  headers: AxiosRequestHeaders;
}
// 添加请求拦截器
instance.interceptors.request.use(
  function (config: MyAxiosRequestConfig) {
    config.url = (config?.api || constants.BASE_URL_API) + config.url;
    return config;
  },
  function (error: any) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    // 图片地址替换
    return response;
  },
  function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);

const userInfo = useUserInfo();
const getHeaders = (headers: any) => {
  return Object.assign(
    {
      uid: userInfo.state.uid || '',
      rid: userInfo.state.rid || '',
    },
    headers
  );
};

export const get = (url: string, data: any, opt: any = {}): Promise<any> => {
  return instance({
    url: (opt.api || constants.BASE_URL_API) + url,
    params: { paras: data },
    ...opt,
    headers: getHeaders(opt?.headers || {}),
  });
};
export const post = async (url: string, data: any, opt: any = {}): Promise<any> => {
  return instance({
    url: url,
    method: 'post',
    data: { paras: data },
    ...opt,
    headers: getHeaders(opt?.headers || {}),
  });
};

export const request = { get, post };
